package top.yueyazhui.word_freemarker.service.impl;

import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import top.yueyazhui.word_freemarker.service.IExportDocService;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.Map;

@Service
public class ExportDocServiceImpl implements IExportDocService {

    @Autowired
    FreeMarkerConfigurer freeMarkerConfigurer;

    public Template getTemplate(String name) throws IOException {
        return freeMarkerConfigurer.getConfiguration().getTemplate(name);
    }

    @Override
    public void exportDocToClient(HttpServletResponse response, String fileName, String tplName, Map<String, Object> data) throws Exception {
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/msword");
//        response.setContentType("application/msexcel");
        response.setHeader("Content-Disposition", "attachment;filename=" +  URLEncoder.encode(fileName, "UTF-8"));
        // 把本地文件发送给客户端
        Writer writer = response.getWriter();
        Template template = getTemplate(tplName);
        template.process(data, writer);
        writer.close();
    }
}
